package com.tgy.algorithm.base;

public class _返回有环链表的第一个节点 {

    public static Node generateLinked(int[] nums) {

        if (nums == null || nums.length == 0){
            return null;
        }

        Node header = new Node(nums[0], null);
        Node curNode = header;
        for (int i = 1; i < nums.length; i++) {
            Node newNode = new Node(nums[i], null);
            curNode.next = newNode;
            curNode = newNode;
        }

        curNode.next = header.next.next.next;
        return header;
    }

    // 获取有环链表第一个入环的节点
    public static Node getCircle(Node head) {
        if (head == null){
            return head;
        }
        Node slow = head;
        Node fast = head;

        do {
            slow = slow.next;
            if (fast == null || fast.next == null){
                return null;
            }
            fast = fast.next.next;
        }while (slow != fast);
        slow = head;
        while (slow != fast){
            slow = slow.next;
            fast = fast.next;
        }
        return slow;
    }

    public static void main(String[] args) {
        int[] nums = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
        Node node = generateLinked(nums);
        Node circleNode = getCircle(node);
        System.out.println(circleNode);
    }
}
